#!/bin/bash
# Script for open CUPS webpage and install it if not installed
# If cups is running open x-www-browser in https://localhost:631
# If cups is not installed installl cups and open browser

# NO CUPS INSTALLED
if [ "$1" = "-I" ]; then
    # INSTALL CUPS
    if ! dpkg -l cups &>/dev/null | grep -q "^ii"; then
        # Install package
		clear
		echo
		echo "  INSTALL PRINTING SUPPORT"
		echo "  ------------------------"
        echo "  CUPS Printing System is not installed"
		echo
        while true; do
            read -p "  Install CUPS? (Y/n) " q;

            [ "${q,,}" = "n" ] && exit
            ([ ! "$q" ] || [ "${q,,}" = "y" ]) && break
        done
        echo
        sudo apt-get install -y cups || exit 1

        # Adduser to lpadmin    
		clear
		echo	
		echo "  SELECT USERS FOR ADMIN PRINTERS"
		echo "  -------------------------------"
        echo "  Users must allow to lpadmin group in order to admin printers"
		echo
        read -p "  Users (space separated): " ul
        for u in $ul; do
            sudo adduser $u lpadmin
        done

        # Open browser
        echo
        read -p "Press enter to open CUPS admin page"
         x-www-browser "http://localhost:631"
    # START CUPS
    else
        echo "CUPS is installed but not running"
        read -p "Press enter to try to start CUPS"
        sudo systemctl start cups.service
        sleep 1
        systemctl status cups&>/dev/null && x-www-browser "http://localhost:631"
    fi

# OPEN CUPS ADMIN
elif systemctl status cups&>/dev/null; then
    x-www-browser "http://localhost:631"
    exit

# CALL TO INSTALL CUPS
else
    x-terminal-emulator -e "$(readlink -f "$0")" -I
fi
